//
//  LatestViewController.m
//  LiveDailyNews
//
//  Created by smu on 11-7-19.
//  Copyright 2011年 duk. All rights reserved.
//

#import "NewsViewController.h"
#import "Constant.h"
#import "RSSItem.h"
#import "WebViewController.h"
#import "FirstCell.h"
#import "CustomCell.h"

@implementation NewsViewController
@synthesize itemList;

@synthesize rssItem;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //工具栏，当前选项卡
        self.tabBarItem.title = @"最新";
        
        UIImage *imageTab = [[UIImage alloc] initWithContentsOfFile:
                             [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"TAB_ICON_CHAT.png"]];
		self.tabBarItem.image = imageTab;
		[imageTab release];
        
        //导航栏添加内容
        //左边logo
        UIImage *logoImage = [[UIImage alloc] initWithContentsOfFile:[
                                                                      [[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Logo.png"]];
        UIImageView *logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 32)];  
        logoImageView.image = logoImage;
        [logoImage release];
        UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:logoImageView]; 
        [logoImageView release];
        self.navigationItem.leftBarButtonItem = leftBarButton;
        [leftBarButton release];
        
        
        //中间标题
        self.navigationItem.title = @"最新";
        
        //右边刷新按钮
        refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self 
                                                                      action:@selector(refreshList:)];
        
        [[self navigationItem] setRightBarButtonItem:refreshButton];
        //ActivityIndicator
        spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
        // I do this because I'm in landscape mode        
        [spinner setCenter:CGPointMake(320/2.0, 480/2.0)];
        // spinner is not visible until started
        [self.view addSubview:spinner];
        
                
        
    }
    return self;
}


- (void)viewDidLoad
{
    //获取整个手机屏幕
    UIView *contentView = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
	
	contentView.autoresizesSubviews = YES;
	self.view = contentView;
	[self.view setBackgroundColor:[UIColor clearColor]];
/*    
	CGRect frame = contentView.frame;
	frame.origin.x = 0;
	frame.origin.y = contentView.bounds.size.height - frame.size.height+25;
	frame.size.width = contentView.bounds.size.width;
	frame.size.height = contentView.bounds.size.height - 44 - 48-25;
*/	
	mtableView = [[UITableView alloc] initWithFrame:
                  CGRectMake(0, 25, contentView.bounds.size.width, contentView.bounds.size.height - 44 - 48-25) style:UITableViewCellStyleDefault];
	mtableView.delegate = self;
	mtableView.dataSource = self;
	mtableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	mtableView.scrollEnabled = YES;
	[mtableView setBackgroundColor:[UIColor clearColor]];
    
	[self.view addSubview:mtableView];
    
    
    UIView *categoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, contentView.bounds.size.width, 25.0)];
    UIImage *scrollmenubg = [UIImage imageNamed:@"scrollmenubg.png"];

    [categoryView setBackgroundColor:[UIColor colorWithPatternImage:scrollmenubg]];
    
    
    leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 25.0)];
    UIImage *leftImage = [UIImage imageNamed:@"right_flag.png"];
    leftImageView.image = leftImage;
   
    
    rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(contentView.bounds.size.width-20, 0, 20, 25.0)];
    UIImage *rightImage = [UIImage imageNamed:@"right_flag.png"];
    rightImageView.image = rightImage;
   
    
    scrolllView = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 0, contentView.bounds.size.width-40, 25.0)];
    scrolllView.alwaysBounceHorizontal = YES;
    //可以滚动的内容
    scrolllView.contentSize = CGSizeMake(400, 25);
    scrolllView.delegate = self;
    
    
    UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 25.0)];
    [button1 setTitle:@"最新" forState:UIControlStateNormal];
    //UIColor里的RGBA是0～1，不是0～255
    //[UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]；
    [button1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    button1.titleLabel.font = [UIFont fontWithName:@"Arial" size:13];
    [scrolllView addSubview:button1];
    //单击触发事件
    [button1 addTarget:self action:@selector(refreshList:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(45, 0, 40, 25.0)];
    [button2 setTitle:@"国内" forState:UIControlStateNormal];
    button2.titleLabel.font = [UIFont fontWithName:@"Arial" size:14];
    
    [scrolllView addSubview:button2];
    
    UIButton *button3 = [[UIButton alloc] initWithFrame:CGRectMake(90, 0, 40, 25.0)];
    [button3 setTitle:@"娱乐" forState:UIControlStateNormal];
    button3.titleLabel.font = [UIFont fontWithName:@"Arial" size:14];

    [scrolllView addSubview:button3];
    
    
    UIButton *button4 = [[UIButton alloc] initWithFrame:CGRectMake(135, 0, 40, 25.0)];
    [button4 setTitle:@"体育" forState:UIControlStateNormal];
    button4.titleLabel.font = [UIFont fontWithName:@"Arial" size:14];

    [scrolllView addSubview:button4];
    
    
    UIButton *button5 = [[UIButton alloc] initWithFrame:CGRectMake(180, 0, 40, 25.0)];
    [button5 setTitle:@"国际" forState:UIControlStateNormal];
    
    [scrolllView addSubview:button5];
    
    
    UIButton *button6 = [[UIButton alloc] initWithFrame:CGRectMake(225, 0, 40, 25.0)];
    [button6 setTitle:@"评论" forState:UIControlStateNormal];
    
    [scrolllView addSubview:button6];
    
    UIButton *button7 = [[UIButton alloc] initWithFrame:CGRectMake(280, 0, 40, 25.0)];
    [button7 setTitle:@"国际" forState:UIControlStateNormal];
    
    [scrolllView addSubview:button7];
    [button7 addTarget:self action:@selector(refreshList:) forControlEvents:UIControlEventTouchUpInside];
   
    
    [categoryView addSubview:leftImageView];
    [categoryView addSubview:rightImageView];
    [categoryView addSubview:scrolllView];
    
    [self.view addSubview:categoryView];
    
//    NSArray *scroll = [[NSBundle mainBundle] loadNibNamed:@"CategoryScrollBar" owner:self options:nil];
//    for (id oneObject in scrollNib)
//        if ([oneObject isKindOfClass:[CustomCell class]]) {
//            cell = (CustomCell *)oneObject;
//        }
    
    [super viewDidLoad];
    
    //初始,下载数据
    mParser = [[RSSParser alloc] init];
    [mParser parse:RSS_HAPPY_URL withDelegate:self onComplete:@selector(refreshTable:)];
    [refreshButton setEnabled:NO];
    [spinner startAnimating];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    
}       


 

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //滑动最右边，隐藏标签
    if (scrolllView.contentOffset.x >= 120.00) {
        rightImageView.hidden = YES;
        NSLog(@"didEndDragging");
        
    } else if(scrollView.contentOffset.x <= 0.00) {
        leftImageView.hidden = YES;
    } else {
        rightImageView.hidden = NO;
        leftImageView.hidden = NO;
    }
        
}





//- (void)menuClicked:(id)vSender
//{
//    NSLog(@"testesttttttt");
//}
     
//
//- (void)viewWillAppear:(BOOL)animated
//{
//    //视图显示时加载数据
//    mParser = [[RSSParser alloc] init];
//    [mParser parse:RSS_LATEST_URL withDelegate:self onComplete:@selector(refreshTable:)];
//}



// This refreshes the feeds when the refresh button is tapped.
- (void)refreshList:(id)sender {
    NSLog(@"%f",scrolllView.contentOffset.x);
    //改变导航栏标题
    self.navigationItem.title = @"国内新闻";
    [refreshButton setEnabled:NO];
	[spinner startAnimating];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
	[mParser release];
    mParser = [[RSSParser alloc] init];
    
	[mParser parse:RSS_HAPPY_URL withDelegate:self onComplete:@selector(refreshTable:)];
    
}

- (void)refreshTable:(RSSParser *)objectParser {
    //判断网络连接，获取数据是否成功
    
    //返回成功
    self.itemList = [objectParser getItems];
    
	[mtableView reloadData];
    
    //重新设置刷新状态
	[refreshButton setEnabled:YES];
	[spinner stopAnimating];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    self.itemList = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc
{
    [itemList release];
    [spinner release];
    [refreshButton release];
    [mtableView release];
    [super dealloc];
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.itemList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    NSUInteger row = [indexPath row];
    rssItem = [itemList objectAtIndex:row];
    static NSString *tableIdentifier;
    
    if (row == 0) {
        tableIdentifier = @"FirstTableIdentifier";
        FirstCell *cell = (FirstCell *)[tableView dequeueReusableCellWithIdentifier:tableIdentifier];
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FirstCell" owner:self options:nil];
            for (id oneObject in nib)
                if ([oneObject isKindOfClass:[FirstCell class]]) {
                    cell = (FirstCell *)oneObject;
                }
            cell.titleLabel.text = rssItem.title;
            
            UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:rssItem.imagePath]]];
            cell.backgroundImageView.image = image;
            cell.descripLabel.text = rssItem.description;
            return cell;
        } else {
            return cell;
        }
        
    } else {
        tableIdentifier = @"CustomTableIdentifier";
        CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:tableIdentifier];
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
            for (id oneObject in nib)
                if ([oneObject isKindOfClass:[CustomCell class]]) {
                    cell = (CustomCell *)oneObject;
                }
            UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:rssItem.imagePath]]];
            cell.titleLabel.text = rssItem.title;
            cell.itemImageView.image = image;
            cell.descripLabel.text = rssItem.description;
            return cell;
        } else {
            return cell;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    rssItem = [itemList objectAtIndex:row];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:rssItem.title forKey:@"title"];
    [userDefaults setObject:rssItem.link forKey:@"link"];
    [userDefaults setObject:rssItem.content forKey:@"content"];
    [userDefaults setObject:rssItem.imagePath forKey:@"imagePath"];
    [userDefaults setObject:rssItem.pubDate forKey:@"pubDate"];
    [userDefaults setObject:rssItem.category forKey:@"category"];
    [userDefaults setObject:rssItem.description forKey:@"description"];
    WebViewController *webView = [[WebViewController alloc] init];
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webView animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([indexPath row] == 0) {
        return 160;
    } else {
        return 70;
    }
}

@end
